package com.sunkyc.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import com.sunkyc.commons.annotation.ReqLog;
import com.sunkyc.commons.entity.R;
import com.sunkyc.commons.exception.CustomerException;
import com.sunkyc.framework.system.entity.LoginUserInfoVo;
import com.sunkyc.framework.system.entity.vo.UpdatePasswordVo;
import com.sunkyc.framework.system.service.LoginService;
import com.sunkyc.framework.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class LoginUserInfoController {
    private final SysUserService sysUserService;
    private final LoginService loginService;


    @GetMapping("/getUserInfo")
    public R<Map<String,Object>> getUserInfo(){
        LoginUserInfoVo userInfo = sysUserService.getUserInfo(StpUtil.getLoginIdAsLong());
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("roles",StpUtil.getRoleList());
        map.put("perms",StpUtil.getPermissionList());
        return R.ok(map);
    }



    @GetMapping("/getRouter")
    public R<List<Tree<Long>>> getRouter(){
        return R.ok( loginService.buildRouterTreeByUser(StpUtil.getLoginIdAsLong()));
    }

    @PostMapping("/resetPwd")
    @ApiOperation("修改密码")
    public R<Void> updatePwd(@RequestBody @Validated UpdatePasswordVo updatePasswordVo){
        if(!updatePasswordVo.getNewPwd().equals(updatePasswordVo.getNewPwdOnce())){
            throw new CustomerException("修改失败，请重新修改");
        }
        long currentId = StpUtil.getLoginIdAsLong();
        return R.result(sysUserService.updatePwd(currentId,updatePasswordVo));
    }

    @PostMapping("/resetAvatar")
    @ApiOperation("上传头像")
    @ReqLog
    public R<Void> resetAvatar(@RequestBody @Validated Map<String,Object> map){
        String avatar = (String) map.get("avatar");
        if(StrUtil.isBlank(avatar))
            throw new CustomerException("头像上传失败");
        long currentId = StpUtil.getLoginIdAsLong();
        return R.result(sysUserService.resetAvatar(currentId,avatar));
    }



}
